package com.future.mayi.activity;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.constant.AppCst;
import com.future.mayi.model.OrderAddModel;
import com.future.mayi.model.RechargeModel;
import com.future.mayi.model.WxPayModel;
import com.future.mayi.model.eventmodel.WxPayResultModel;
import com.future.mayi.response.OrderAddResponse;
import com.future.mayi.response.RechargeListResponse;
import com.future.mayi.utils.PayResult;
import com.future.mayi.utils.PriceUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class RechargeActivity extends BaseTitleActivity {
    @BindView(R.id.ll_pay_num)
    LinearLayout llPayNum;
    @BindView(R.id.tv_ali_pay)
    TextView tvAliPay;
    @BindView(R.id.tv_weixin_pay)
    TextView tvWeixinPay;
    @BindView(R.id.tv_yinlian_pay)
    TextView tvYinlianPay;
    @BindView(R.id.tv_enter)
    TextView tvEnter;

    private LayoutInflater mInflater;
    private int position;

    private IWXAPI wxApi;

    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("充值");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_recharge);
    }

    @Override
    protected void initView() {
        mInflater = LayoutInflater.from(this);
    }

    @Override
    protected void initDates() {
        getRechargeList();
        setSelectPay(1);
    }

    @Override
    protected void initListener() {
        EventBus.getDefault().register(this);
    }


    @OnClick({R.id.tv_ali_pay, R.id.tv_weixin_pay, R.id.tv_yinlian_pay, R.id.tv_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ali_pay:
                setSelectPay(1);
                break;
            case R.id.tv_weixin_pay:
                setSelectPay(2);
                break;
            case R.id.tv_yinlian_pay:
                setSelectPay(3);
                break;
            case R.id.tv_enter:
                tvEnter.setEnabled(false);
                if (list == null || list.size() == 0) {
                    toast("正在加载中");
                    tvEnter.setEnabled(true);
                    return;
                }
                enter();
                break;
        }
    }


    private int selectPay;

    private void setSelectPay(int selectPay) {
        if (selectPay == this.selectPay) return;
        this.selectPay = selectPay;
        if (selectPay == 2 && wxApi == null) {
            wxApi = WXAPIFactory.createWXAPI(this, AppCst.Wechat_APP_ID);
        }
        setSelectPayTextView(selectPay == 1, tvAliPay);
        setSelectPayTextView(selectPay == 2, tvWeixinPay);
        setSelectPayTextView(selectPay == 3, tvYinlianPay);
    }

    private void setSelectPayTextView(boolean select, TextView textView) {
        Drawable drawableLeft = null;
        if (textView == tvAliPay)
            drawableLeft = getResources().getDrawable(R.drawable.zhifu_zhifubao);
        if (textView == tvWeixinPay)
            drawableLeft = getResources().getDrawable(R.drawable.zhifu_weiixn);
        if (textView == tvYinlianPay)
            drawableLeft = getResources().getDrawable(R.drawable.zhifu_yinghangka);
        if (drawableLeft != null)
            drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());

        Drawable drawableRight = select ? getResources().getDrawable(R.drawable.tab_selected) : getResources().getDrawable(R.drawable.tab_normal);
        drawableRight.setBounds(0, 0, drawableRight.getMinimumWidth(), drawableRight.getMinimumHeight());
        textView.setCompoundDrawables(drawableLeft, null, drawableRight, null);
    }


    @SuppressWarnings("unchecked")
    private void getRechargeList() {
        new HttpRequest<RechargeListResponse>()
                .with(getActivity())
                .setApiCode(ApiCst.getRechargeList)
                .setListener(new HttpRequest.OnNetworkListener<RechargeListResponse>() {

                    @Override
                    public void onSuccess(RechargeListResponse response) {
                        list = response.list;
                        setPayItemView();
                    }

                    @Override
                    public void onFail(String message, RechargeListResponse response) {

                    }
                }).start(new RechargeListResponse());
    }


    private List<RechargeModel> list;
    private List<ImageView> imageViews;
    private List<View> viewList;

    private void setPayItemView() {
        if (list == null || list.size() == 0) return;
        imageViews = new ArrayList<>();
        viewList = new ArrayList<>();
        llPayNum.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            RechargeModel model = list.get(i);
            View view = mInflater.inflate(R.layout.layout_pay_item, llPayNum, false);
            ImageView ivSelect = (ImageView) view.findViewById(R.id.iv_select);
            TextView tvMoney = (TextView) view.findViewById(R.id.tv_money);
            TextView tvYouhui = (TextView) view.findViewById(R.id.tv_youhui);
            tvMoney.setText(PriceUtils.getPriceText(model.getPrice()));
            if (model.getGive() > 0) {
                tvYouhui.setVisibility(View.VISIBLE);
                tvYouhui.setText("充值即送¥" + PriceUtils.getPriceText(model.getGive()));
            }
            view.setTag(i);
            view.setOnClickListener(this);
            if (i == 0) {
                ivSelect.setVisibility(View.VISIBLE);
                tvMoney.setTextColor(getResources().getColor(R.color.main_color));
                view.setBackgroundColor(getResources().getColor(R.color.bg_ffebc8));
            }
            viewList.add(view);
            imageViews.add(ivSelect);
            llPayNum.addView(view);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getTag() != null && v.getTag() instanceof Integer) {
            position = (int) v.getTag();
            for (int i = 0; i < list.size(); i++) {
                if (position == i) {
                    imageViews.get(i).setVisibility(View.VISIBLE);
                    viewList.get(i).setBackgroundColor(getResources().getColor(R.color.bg_ffebc8));
                } else {
                    imageViews.get(i).setVisibility(View.INVISIBLE);
                    viewList.get(i).setBackgroundColor(getResources().getColor(R.color.white));
                }
            }
        }
    }


    private void enter() {
        double total_price = 0;
        RechargeModel rechargeModel = list.get(position);
        total_price = rechargeModel.getPrice();
        new HttpRequest<OrderAddResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .addParam("pay_type", selectPay)
                .addParam("total_price", total_price)
                .addParam("platform", 0)
                .setApiCode(ApiCst.refWallet)
                .setListener(new HttpRequest.OnNetworkListener<OrderAddResponse>() {
                    @Override
                    public void onSuccess(OrderAddResponse response) {
                        dissmissLoadingDialog();
                        //1-支付宝 2-微信 3-余额 4-银联 10-分期
                        if (response.getOrderAddModel() == null) {
                            toast("提交订单失败");
                            return;
                        }
                        pay(response.getOrderAddModel());
                    }

                    @Override
                    public void onFail(String message, OrderAddResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .start(new OrderAddResponse());

        tvEnter.setEnabled(true);

    }

    private void pay(OrderAddModel orderAddModel) {
        switch (selectPay) {
            case 1:
                payBuyAliPay(orderAddModel.getAlipay_info());
                break;
            case 2:
                payBuyWechatPay(orderAddModel.getWx_pay_info());
                break;
            case 3:
                break;
            case 4:
                //银行卡
                break;
        }
    }


    // ----------------------------------------------------阿里支付-------------------------------------------------------

    private static final int SDK_PAY_FLAG = 1;

    private void payBuyAliPay(final String orderInfo) {
        if (TextUtils.isEmpty(orderInfo)) {
            toast("订单支付失败");
            return;
        }

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                pHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler pHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paySuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        payError();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };
    // ----------------------------------------------------阿里支付-------------------------------------------------------


    // ----------------------------------------------------微信支付-------------------------------------------------------
    private void payBuyWechatPay(WxPayModel model) {
        PayReq req = new PayReq();
        req.appId = model.getAppid();
        req.partnerId = model.getPartnerid();
        req.prepayId = model.getPrepayid();
        req.nonceStr = model.getNoncestr();
        req.timeStamp = model.getTimestamp();
        req.sign = model.getSign();
        req.extData = "app data";
        req.packageValue = model.getPackageX();
        //发起支付请求
        wxApi.sendReq(req);
    }
    // ----------------------------------------------------微信支付-------------------------------------------------------


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void downloadEvent(WxPayResultModel messageEvent) {
        if (messageEvent.errCode == 0)
            paySuccess();
        else if (messageEvent.errCode == -1)
            payError();
        else if (messageEvent.errCode == -2)
            payCancel();
    }


    private void payCancel() {
        toast("支付取消");
    }

    private void payError() {
        toast("支付失败");
    }

    private void paySuccess() {
        toast("支付成功");
        this.finish();
    }
}
